package com.biostime.dingdingbox.modules.sys.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.dingdingbox.common.config.Global;
import com.biostime.dingdingbox.common.persistence.Page;
import com.biostime.dingdingbox.common.utils.StringUtils;
import com.biostime.dingdingbox.common.web.BaseController;
import com.biostime.dingdingbox.modules.sys.entity.Role;
import com.biostime.dingdingbox.modules.sys.entity.User;
import com.biostime.dingdingbox.modules.sys.service.RoleService;
import com.biostime.dingdingbox.modules.sys.service.SystemService;
import com.biostime.dingdingbox.modules.sys.service.UserRoleService;
import com.biostime.dingdingbox.modules.sys.service.UserService;
import com.biostime.dingdingbox.modules.sys.utils.UserUtils;

/**
 * 用户表Controller
 * @author king
 * @version 2015-11-12
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	
	@ModelAttribute
	public User get(
			@RequestParam(required=false) String id,
			@RequestParam(required=false) String centerId) {
		
		User entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = userService.get(id);
		}
		if (entity == null){
			entity = new User();
		}
				
		return entity;
	}
	
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = {"ajax"})
	public void ajax(HttpServletRequest request, HttpServletResponse response) {
		try {
			String method = request.getParameter("method");
			
			if(StringUtils.isEmpty(method)){
				response.getWriter().write("缺少method参数");
				return;
			}
			
			if(method != null && method.equalsIgnoreCase("user_validate")){
				String loginName = request.getParameter("param");
				
				boolean res = false;
				if(!StringUtils.isEmpty(loginName)){
					res = userService.validate(loginName);
				}else{
					response.getWriter().write("{ \"info\":\"用户名不可为空\", \"status\":\"n\" }");
					return;
				}
				
				if(res){
					response.getWriter().write("{ \"info\":\"该登录名已被注册\", \"status\":\"n\" }");
				}else{
					response.getWriter().write("{ \"info\":\"该登录名可用\", \"status\":\"y\" }");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("changepwd")
	public String changePwd(User user, HttpServletRequest request,Model model){
		String oldPassword = request.getParameter("oldpassword");
		user = UserUtils.getUser();
		if(oldPassword != null && !oldPassword.equals("")){
				if(SystemService.validatePassword(oldPassword, user.getPassword())){
					String password1 = request.getParameter("password1");
					String password2 = request.getParameter("password2");
					if(password1 != null && password2 != null && password1.equals(password2)){
						userService.changePwd(user,password1,oldPassword);
						model.addAttribute("message", "修改密码成功");
					}else{
						model.addAttribute("message", "修改密码失败,原因可能是您输入了空格或不允许存在的字符");
					}
				}else{
					model.addAttribute("message", "原密码录入错误");
				}
			}
		
		return "modules/sys/changePwd";
	}
	
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"list", ""})
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		//user.setCenter(UserUtils.getCenter());
		Page<User> page = userService.findPage(new Page<User>(request, response), user); 
		model.addAttribute("page", page);
		return "modules/sys/userList"; 
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		User curUser = UserUtils.getUser();
		/**所有角色**/
		List<Role> roleList = roleService.findListByUser(curUser);
		if(!StringUtils.isEmpty(user.getId())){
			Map<String,String> userRoles = roleService.findMapByUser(user);
			
			for(Role role : roleList){
				if(userRoles.containsKey(role.getId())){
					role.setChecked(true);
				}
			}
		}
			
		model.addAttribute("roleList", roleList);
		model.addAttribute("defaultpassword", UserService.defaultpassword);
		model.addAttribute("user", user);
		return "modules/sys/userForm";
	}

	@RequiresPermissions(value={"sys:user:edit","sys:user:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, user)){
			return form(user, model);
		}
		
		userService.saveUser(user, request);
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, User user, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				userRoleService.deleteUserRole(id);
				userService.delete(new User(id));
			}
		}else{
			userRoleService.deleteUserRole(user.getId());
			userService.delete(user);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/sys/user/?repage";
	}
	


}